package com.jsy.seckill.task;

import com.jsy.common.constant.SeckillConstant;
import com.jsy.common.util.DateUtil;
import com.jsy.seckill.dao.SeckillGoodsMapper;
import com.jsy.seckill.pojo.SeckillGoods;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import tk.mybatis.mapper.entity.Example;

import java.util.Date;
import java.util.List;
import java.util.Set;

@Component
public class SeckillGoodsTask {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private SeckillGoodsMapper seckillGoodsMapper;

    @Scheduled(cron = "0 * * * * ?")
    public void loadGoodsToRedis() {
        //1.计算秒杀时间段
        List<Date> dateMenus = DateUtil.getDateMenus();
        for (Date activeStartTime : dateMenus) {
            Example example = new Example(SeckillGoods.class);
            Example.Criteria criteria = example.createCriteria();
            //2.状态必须审核通过
            criteria.andEqualTo("status", "1");
            //3.商品库存个数>0
            criteria.andGreaterThan("stockCount", 0);
            //4.活动没结束
            criteria.andGreaterThan("startTime", activeStartTime);
            criteria.andLessThan("endTime", DateUtil.addDateHour(activeStartTime, 2));
            //5.在Redis中没有该商品缓存
            String timeStr = DateUtil.date2str(activeStartTime, DateUtil.PATTERN_YYYYMMDDHH);
            Set set = redisTemplate.boundHashOps(SeckillConstant.SECKILL_GOODS_PREFIX + timeStr).keys();
            if (set != null && set.size() > 0) {
                criteria.andNotIn("id", set);
            }
            //6.执行查询结果获得对应的结果集
            List<SeckillGoods> seckillGoodsList = seckillGoodsMapper.selectByExample(example);
            //7.将查询结果更新到redis中
            if (seckillGoodsList != null && seckillGoodsList.size() > 0) {
                for (SeckillGoods seckillGoods : seckillGoodsList) {
                    redisTemplate.boundHashOps(SeckillConstant.SECKILL_GOODS_PREFIX + timeStr).put(seckillGoods.getId(), seckillGoods);
                }
            }
        }
    }


}
